import json

from django.shortcuts import render, get_object_or_404
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from management.models import Role
from management.serializers import RoleSerializer
from workflow import models, serializers


# Create your views here.

class WorkflowView(APIView):
    def get(self, request):
        workflows = models.Workflow.objects.all()
        ser = serializers.WorkflowSerializer(workflows, many=True)
        return Response({"code": 200, "data": ser.data})

    def post(self, request):
        name = request.data.get('name')
        params = request.data.get('params')
        params = json.dumps(params)
        ser = serializers.WorkflowSerializer(data={"name": name, "params": params, "status": 1})
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, "data": ser.data})
        else:
            return Response({"code": 400, "data": ser.errors})


class WorkflowApprovalConfigView(APIView):
    def get(self, request, workflow_id):
        print(workflow_id)
        # 存储最终结果的列表
        result = []
        if workflow_id:
            try:
                # 查询指定工作流
                workflow = models.Workflow.objects.get(id=workflow_id)
                # 存储该工作流的角色审批信息
                workflow_approval_info = {
                    "workflow_name": workflow.name,
                    "approval_priorities": []
                }
                # 查询该工作流关联的所有工作流审批节点
                approval_nodes = models.WorkflowApprovalNode.objects.filter(workflow_id=workflow)
                for node in approval_nodes:
                    role = node.role_id
                    priority = node.level
                    # 将角色名称和优先级添加到该工作流的信息中
                    workflow_approval_info["approval_priorities"].append({
                        "role_name": role.name,
                        "priority": priority
                    })
                result.append(workflow_approval_info)
            except models.Workflow.DoesNotExist:
                return Response({"error": "工作流不存在"}, status=404)
        else:
            # 查询所有角色
            roles = Role.objects.all()
            for role in roles:
                # 存储该角色在不同工作流中的审批优先级信息
                role_approval_info = {
                    "role_name": role.name,
                    "approval_priorities": []
                }
                # 查询该角色关联的所有工作流审批节点
                approval_nodes = models.WorkflowApprovalNode.objects.filter(role_id=role)
                for node in approval_nodes:
                    workflow = node.workflow_id
                    priority = node.level
                    # 将工作流名称和优先级添加到该角色的信息中
                    role_approval_info["approval_priorities"].append({
                        "workflow_name": workflow.name,
                        "priority": priority
                    })
                result.append(role_approval_info)
        return Response({"code": 200, "result": result})

    def post(self, request):
        # 获取前端传来的数据
        workflow_id = request.data.get('workflow_id')
        role_ids = request.data.get('role_ids', [])
        try:
            # 查找工作流
            workflow = models.Workflow.objects.get(id=workflow_id)
        except models.Workflow.DoesNotExist:
            return Response({"error": "工作流不存在"}, status=status.HTTP_404_NOT_FOUND)

        # 先删除该工作流的现有审批配置
        models.WorkflowApprovalNode.objects.filter(workflow_id=workflow).delete()

        try:
            # 遍历角色 id 列表
            for index, role_id in enumerate(role_ids):
                # 查找角色
                role = Role.objects.get(id=role_id)
                # 创建工作流审批节点
                models.WorkflowApprovalNode.objects.create(
                    workflow_id=workflow,
                    role_id=role,
                    level=index + 1
                )
        except Exception as e:
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response({"code": 200, "message": "审批流程配置成功"})
